<template>
	<view class="container">

		<!-- 需要引用uview的popup弹窗组件，或者也可替换成其他的弹窗组件，这里按照你使用的ui框架稍加修改即可 -->
		<!-- 如需安装uview-ui，官网: https://v1.uviewui.com/components/npmSetting.html -->

		<!-- <u-popup v-model="visible" mode="bottom" border-radius="20" @close="$emit('close')"> -->

		<view class="tmt-header t-c">
			<!-- <view class="left" @click="$emit('close')">
					取消
				</view> -->
			<view class="t-c title">
				<view class="next flex-center" @click="changMonth(1)">
					<image src="@/static/xiaLa.png" class="arrow-icon right-icon"></image>
				</view>
				<view class="date" style="width: 50%;" @click="onDateTitle">
					{{ `${currentYearMonth.year}年${currentYearMonth.month>=10?currentYearMonth.month:'0'+currentYearMonth.month}月` }}
				</view>
				<view class="prev flex-center" @click="changMonth(-1)">
					<image src="@/static/xiaLa.png" class="arrow-icon left-icon"></image>
				</view>
			</view>
			<!-- <view class="right" @click="confirm">
					确认
				</view> -->
		</view>

		<view class="tmt-content">
			<view class="tmt-week-wrap" v-if="isWeek">
				<view class="cell week-item" :style="{color:weekColor}" v-for="(item,weekListIndex) in week"
					:key="weekListIndex">{{ item.label }}</view>
			</view>
			<view class="tmt-day-wrap" :style="[{color:dayColor}]">
				<view class="cell" v-for="(blankItem,blankIndex) of blankDay" :key="`${blankItem}/${blankIndex}`">
				</view>
				<view v-for="(item, index) in daysArr" :key="index" class="cell" @click="changeDay(item, index)">
					<!-- <view class="cell" v-for="(item,dayIndex) in daysArr" :key="dayIndex"
						@click="changeDay(item,dayIndex)"> -->
					<!-- 显示带宽 -->
					<view class="dayText active-select Column" v-if="item.active">
						<view class="">{{ item.day }}</view>
						<view v-if="item.bandwidth !== null" class="bandwidth-text" style="color: #fff;">
							+{{ item.bandwidth }}
						</view>
					</view>
					<view
						:class=" item.bandwidth !== null ? 'dayText can-selects Column' : 'dayText can-select Column' "
						v-else-if="selectShow(item)">
						<view class="">{{ item.day }}</view>
						<text v-if="item.bandwidth !== null" class="bandwidth-text">
							+{{ item.bandwidth }}
						</text>
					</view>
					<view class="dayText Column" v-else>
						<view class="">{{ item.day }}</view>
						<text v-if="item.bandwidth !== null" class="bandwidth-text">
							+{{ item.bandwidth }}
						</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 			<view class="buttom-btn" >
				<slot name="bottomContent"></slot>
			</view> -->

		<!-- </u-popup> -->

	</view>
</template>

<script>
	export default {
		name: "calendar",
		data() {
			return {
				monthBandwidthList: [], //  月数据

				visible: true,
				week: [{
						label: '日',
						value: 7
					}, {
						label: '一',
						value: 1
					},
					{
						label: '二',
						value: 2
					},
					{
						label: '三',
						value: 3
					},
					{
						label: '四',
						value: 4
					},
					{
						label: '五',
						value: 5
					},
					{
						label: '六',
						value: 6
					},

				],
				blankDay: 0, //空白天数
				today: {}, //当天
				current: {}, //当前的年月
				daysArr: [],
				list: [], //需要下标的日期
				currentYearMonth: {}, //当前年月
				currentDate: {
					year: "",
					month: "",
					day: ""
				},
				activeList: []
			};
		},
		computed: {
			contentHeight() {
				let height = Math.ceil((this.blankDay + this.daysArr.length) / 7) * 88
				return height + 'rpx'
			},
		},
		watch: {
			defaultDate(val) {
				this.init("")
			}
		},
		props: {
			selectList: {
				type: Array,
				default () {
					return []
				}
			},
			// 默認時間，月份初始化
			defaultDate: {
				type: String,
				default () {
					return ''
				}
			},
			// 默認日子，高亮選中
			defaultDay: {
				type: String,
				default () {
					return ''
				}
			},
			weekColor: {
				type: String,
				default () {
					return '#000'
				}
			},
			dayColor: {
				type: String,
				default () {
					return '#000'
				}
			},
			isSingle: {
				type: Boolean,
				default: true
			},
			isWeek: {
				type: Boolean,
				default: true
			},
			isDateExpire: {
				type: Boolean,
				default: false
			}
		},
		created() {
			let that = this;
			uni.$on('monthlyData', function(data) {
				that.monthBandwidthList = data.monthBandwidthList;

				// 获取当前正在显示的年月，然后重新生成日历
				const {
					year,
					month
				} = that.currentYearMonth;
				that.makeCalendar(year, month);
			});

			// 页面首次加载时，正常初始化
			this.init(this.defaultDate == '');
		},
		mounted() {
			let time = new Date();
			let year = time.getFullYear();
			let month = time.getMonth() + 1;
			let day = time.getDate();
			this.currentDate = {
				year: time.getFullYear(),
				month: month > 9 ? month : '0' + month,
				day: day > 9 ? day : '0' + day,
			}
		},
		methods: {
			onDateTitle() {
				this.$emit("onTitle");
			},
			changMonth(num = 1) {
				const {
					year,
					month
				} = this.getMonthYear(num)
				this.makeCalendar(year, month)
			},
			// 获取前几个月,未来几个月的年份和月份
			getMonthYear(num) {
				let month = this.currentYearMonth.month
				let year = this.currentYearMonth.year
				let year2 = year
				let month2 = month + num
				if (month + num <= 0) {
					// 之前年份
					year2 = year - 1 - parseInt(Math.abs(month2) / 12)
					month2 = 12 - (Math.abs(month2) % 12)
				} else if ((month2 / 12) > 1) {
					// 之后年份
					year2 = year + (month2 % 12 == 0 ? 0 : parseInt(month2 / 12))
					month2 = parseInt(month2 % 12) == 0 ? 12 : parseInt(month2 % 12)
				}
				return {
					year: year2,
					month: month2
				}
			},
			changeDay(item, index) {
				// console.log(item, index)
				if (this.selectList.length >= 1 && this.selectList.findIndex(el => el.date == item.date) == -1) return;

				let {
					year,
					month,
					day
				} = this.currentDate;
				let current = `${year}-${month}-${day} 00:00:00`;
				if (this.isDateExpire && new Date(current).getTime() > new Date(item.date + " 00:00:00").getTime()) {
					uni.showToast({
						title: "日期已过，无法选择",
						icon: 'none'
					})
					return
				}

				if (this.isSingle) {
					this.daysArr.forEach(el => el.active = false);
				}

				this.daysArr[index].active = !this.daysArr[index].active;
				let selectList = [];
				this.daysArr.forEach(el => {
					if (el.active) {
						selectList.push(el)
					}
				})
				this.activeList = selectList;
				this.confirm();
			},
			// 获取某年某月的天数
			getDays(year, month) {
				let now = new Date(year, month, 0)
				return now.getDate()
			},
			//获取某一天为星期几
			getWeekByDay(time) {
				let day = new Date(Date.parse(time.replace(/-/g, '/'))); //将日期值格式化
				return day.getDay() == 0 ? 7 : day.getDay();
			},
			init(nowTime, status = "") {
				let setTime = nowTime ? new Date() : new Date(this.defaultDate)
				let year = setTime.getFullYear()
				let month = setTime.getMonth() + 1
				let day = setTime.getDate();
				if ((!(this.defaultDate != '' && nowTime))) {
					this.current = {
						year,
						month,
						day,
					}
				}
				this.today = {
					year: new Date().getFullYear(),
					month: new Date().getMonth() + 1,
					day: new Date().getDate()
				}
				this.makeCalendar(year, month)
			},
			makeCalendar(year, month) {
				let today = this.today;
				let days = this.getDays(year, month);
				let firstDayWeek = this.getWeekByDay(`${year}-${month}-1`);
				let weekIndex = this.week.findIndex(item => {
					return item.value == firstDayWeek;
				});

				// --- 新增：保存当前已激活的日期 ---
				// 在重建日历前，先记录下当前哪个日期是被选中的
				let currentActiveDate = null;
				if (this.daysArr.length > 0 && this.isSingle) {
					const activeItem = this.daysArr.find(day => day.active);
					if (activeItem) {
						currentActiveDate = activeItem.date; // 保存选中项的 date 字符串
					}
				}
				// --- 新增结束 ---

				let daysArr = [];
				for (let i = 1; i <= days; i++) {
					const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(i).padStart(2, '0')}`;
					const bandwidthData = this.monthBandwidthList.find(item => item.transDate === dateStr);
					const bandwidth = bandwidthData ? parseFloat(bandwidthData.bandwidth) : null;

					// --- 修改：不再在这里设置 active 和 today 标记 ---
					daysArr.push({
						date: dateStr,
						year,
						month,
						day: i,
						bandwidth
						// 注意：这里移除了 active 和 today 属性，稍后统一设置
					});
				}

				this.currentYearMonth = {
					year,
					month
				};
				this.blankDay = weekIndex == -1 ? 0 : weekIndex;

				// --- 新增：统一设置 active 和 today 状态 ---
				// 将构建好的 daysArr 赋值给 this.daysArr，然后再遍历设置状态
				this.daysArr = daysArr;

				// 1. 先设置 today 标记
				this.daysArr.forEach(day => {
					day.today = (year == today.year && month == today.month && day.day == today.day);
				});

				// 2. 再设置 active 状态
				if (this.isSingle) {
					// 如果有保存的选中日期，则激活它
					if (currentActiveDate) {
						this.daysArr.forEach(day => {
							day.active = (day.date === currentActiveDate);
						});
					} else {
						// 如果没有保存的选中日期，则默认激活今天
						this.daysArr.forEach(day => {
							if (day.today) {
								day.active = true;
							}
						});
					}
				}

				// 处理通过 props 传入的 defaultDay
				if (this.defaultDay) {
					this.daysArr.forEach(el => {
						if (el.date == this.defaultDay) {
							el.active = true;
						}
					});
				}
			},
			// makeCalendar(year, month) {
			// 	let today = this.today
			// 	let days = this.getDays(year, month) //当月天数
			// 	let firstDayWeek = this.getWeekByDay(`${year}-${month}-1`) //获取每个月第一天的星期
			// 	let weekIndex = this.week.findIndex(item => {
			// 		return item.value == firstDayWeek
			// 	})
			// 	let daysArr = []
			// 	for (let i = 1; i <= days; i++) {
			// 		daysArr.push({
			// 			date: `${year}-${month>9?month:'0'+month}-${i>9?i:'0'+i}`,
			// 			year,
			// 			month,
			// 			day: i,
			// 			active: false,
			// 			today: year == today.year && month == today.month && i == today.day
			// 		})
			// 	}
			// 	this.currentYearMonth = {
			// 		year,
			// 		month
			// 	}
			// 	this.daysArr = daysArr
			// 	this.blankDay = weekIndex == -1 ? 0 : weekIndex;

			// 	if (this.isSingle) { // 如果是单选模式
			// 		// 遍历所有日期，找到今天，并将其设为激活状态
			// 		this.daysArr.forEach(day => {
			// 			if (day.today) {
			// 				day.active = true;
			// 				// 如果你想让 activeList 也包含初始值，可以在这里添加
			// 				// this.activeList = [day];
			// 			}
			// 		});
			// 	}

			// 	if (this.defaultDay) {
			// 		this.daysArr.forEach((el, index) => {
			// 			if (el.date == this.defaultDay) {
			// 				el.active = true;
			// 			}
			// 		})
			// 	}
			// },
			selectShow(item) {
				if (this.selectList.length == 0) return true;
				return this.selectList.findIndex(el => el.date == item.date) > -1
			},
			confirm() {
				if (this.activeList.length == 0) {
					uni.showToast({
						title: "请选择",
						icon: 'none'
					})
					return
				}
				this.$emit('confirm', this.activeList)
			}


		}
	}
</script>

<style lang="scss" scoped>
	$theme-color: #2391DA;

	.bjFbebec {
		background-color: #fbebec;
	}

	.bjF6f6f6 {
		background-color: #f6f6f6;
	}

	// 带宽文本样式
	.bandwidth-text {
		font-size: 20rpx;
		color: #d35029;
		/* 半透明背景，提高可读性 */
		padding: 2rpx 8rpx;
		border-radius: 4rpx;
		white-space: nowrap;
		/* 防止换行 */
	}

	.tmt-header {
		background-color: #fff;
		border-radius: 6px 6px 0 0;
		padding: 0 20rpx;
		height: 48px;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.title {
			width: 100%;
			height: 48px;
			font-size: 18px;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.prev {
				width: 30%;
				height: 100%;
				color: $theme-color;
			}

			.next {
				width: 30%;
				height: 100%;
				color: $theme-color;
			}
		}

		.left {
			padding: 0 15px;
			color: $theme-color;
			font-size: 14px;
		}

		.right {
			padding: 0 15px;
			color: $theme-color;
			font-size: 14px;
		}

		.arrow-icon {
			width: 16px;
			height: 16px;

			&.right-icon {
				transform: rotate(180deg);
			}
		}
	}

	.p20 {
		padding: 20rpx;
	}

	.cell {
		width: 14.28%;
		height: 84rpx;
		text-align: center;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 5px !important;
		position: relative;

		.dayText {
			width: 84rpx;
			height: 84rpx;
			text-align: center;
			display: flex;
			justify-content: center;
			align-items: center;
			border-radius: 8rpx;
			font-size: 32rpx;
			background-color: #FFFFFF;
			color: #C8C9CC;
			margin-bottom: 5px !important;

			&.active-select {
				color: #fff;
				background: #0056FF;
				box-sizing: border-box;
			}

			&.can-select {
				background-color: #FFFFFF;
				color: #323232;
			}

			&.can-selects {
				background-color: #fbebec;
				color: #323232;
			}
		}

	}

	.tmt-content {
		background: #fff;
		border-radius: 0 0 6px 6px;
		padding: 0 20rpx;

		.tmt-week-wrap {
			display: flex;
			box-shadow: 0px 2px 2px 0px rgba(224, 224, 224, 0.5);

			.week-item {
				color: #323232;
				font-size: 12px;
			}
		}

		.tmt-day-wrap {
			display: flex;
			flex-wrap: wrap;
			transition: height .3s;
			overflow: hidden;
		}
	}


	.buttom-btn {
		width: 100%;
		height: calc(15px + env(safe-area-inset-bottom));
		font-size: 16px;
		font-weight: 700;
		border-top: 8px solid #FFFFFF;
		background-color: #fff;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-bottom: calc(constant(safe-area-inset-bottom));
		padding-bottom: calc(env(safe-area-inset-bottom));
		padding-right: 20px;
	}

	.flex-center {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.t-c {
		text-align: center;
	}

	.title {
		font-weight: bold;
	}
</style>